import functools
from django.core.handlers.wsgi import WSGIRequest
from django.http.request import HttpRequest
from rest_framework.request import Request
from rest_framework.response import Response as rest_response

from core.config import TOKEN_MANAGE
from core.service import PERMISSION_MANAGER

def rpc_validate_permission(key:str):
    def decorator(func):
        @functools.wraps(func)
        def wapper(*args,**kwargs):
            __request= None
            for o in args:
                if isinstance(o,(WSGIRequest,HttpRequest,Request)):
                    __request= o
                    break
            if __request:
                SAAS_HTTP_HEADERS_MANAGE= TOKEN_MANAGE()
                SAAS_HTTP_HEADERS_MANAGE.load(__request)
                state,msg= PERMISSION_MANAGER.validate(
                    group="",
                    permission_key= key
                )
                if state:
                    return func(*args,**kwargs)
                else:
                    return rest_response(
                        data= {
                            "state":-1,
                            "msg":msg
                        },
                        status=200
                    )
            else:
                return rest_response(
                    {
                        "state":-1,
                        "msg":"not found Request object."
                    },
                    200
                )
        return wapper
    return decorator
